<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['code']" placeholder="请输入编码"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['name']" placeholder="请输入名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['warehouse']"  placeholder="请输入仓库"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="货仓" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['house']" placeholder="请输入货仓"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="行" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['row']" placeholder="请输入行"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="层" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['layer']" placeholder="请输入层"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['box']" placeholder="请输入箱"></a-input>
            </a-form-item>
          </a-col>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            :hidden="seen"
            label="上级分类">
            <a-tree-select
              style="width:100%"
              :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
              :treeData="dataSource"
              :loadData="onLoadData"
              v-model="model.parentCode"
              placeholder="无"
              :disabled="condition"
              :loadedKeys="loadedKeys"
            >
            </a-tree-select>
          </a-form-item>
          <a-col :span="24">
            <a-form-item label="库管员" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['storekeeperName']" readOnly @click="onSearchStroageUser" placeholder="请输入库管员"></a-input>
            </a-form-item>
          </a-col>
          <a-input v-decorator="['storekeeperId']" hidden="true" placeholder="请输入库管员ID"></a-input>
          <a-col :span="24">
            <a-form-item label="所属部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['departName']"
                       readOnly @click="onSearchDepart"
                       placeholder="请输入所属部门"></a-input>
            </a-form-item>
          </a-col>
          <a-input v-decorator="['departId']" hidden="true" placeholder="请输入所属部门ID"></a-input>
          <a-col :span="24">
            <a-form-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag :value="'请选择'" :triggerChange="true" dictCode="warehouse_type"
                                 v-decorator="['type',{ rules: [{ required:true, message: '必填项' }] }]" placeholder="请选择类型"/>
            </a-form-item>
          </a-col>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
    <depart-tree-modal ref="departModel" @ok="onDepartOk"></depart-tree-modal>
    <stroage-user-modal ref="stroageUserModel" @ok="onStroageUserOk"></stroage-user-modal>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@lone/lone-vue/src/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@lone/lone-vue/src/utils/util'
  import JFormContainer from '@lone/lone-vue/src/components/jeecg/JFormContainer'
  import DepartTreeModal from '../../base/form/DepartTreeModal'
  import StroageUserModal from '../../base/form/StorageUserModal'

  const checkMmsWzWarehouseInfo = (params)=>getAction("/ck/mmsWzWarehouseInfo/checkOnlyMmsWarehouseCode",params);

  export default {
    name: 'MmsWzWarehouseInfoForm',
    components: {
      JFormContainer,
      DepartTreeModal,
      StroageUserModal
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        storekeeperDictOptions: [],
        visibleCheck: false,
        loadedKeys:[],
        modalWidth:800,
        drawerWidth:700,
        seen:false,
        condition:true,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules:{
          name:{rules: [{ required: true, message: '请输入名称' }]},
          code:{
            rules: [{
              required: true, message: '请输入编码',validator: this.validateCode,
            }]
          },
        },
        url: {
          add: "/ck/mmsWzWarehouseInfo/add",
          edit: "/ck/mmsWzWarehouseInfo/edit",
          queryById: "/ck/mmsWzWarehouseInfo/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      validateCode(rule, value, callback){
        var params = {
          id:this.model.id,
          code:value
        };
        checkMmsWzWarehouseInfo(params).then((res)=>{
          if(res.success){
            callback();
          }else{
            callback("仓库编码已存在！");
          }
        });
      },
      //初始化加载方法
      loadTree (key = '') {
        getAction(`/ck/mmsWzWarehouseInfo/treeList`,{ key }).then((res) => {
          if (res.success) {
            this.dataSource = res.result
          }
        })
      },
      //展开节点调用此方法
      onLoadData (treeNode) {
        return new Promise((resolve) => {
          getAction('/ck/mmsWzWarehouseInfo/treeList',{ key:treeNode.dataRef.key }).then((res) => {
            if (res.success) {
              treeNode.dataRef.children = res.result;
              this.dataSource = [...this.dataSource]
              resolve()
            }
          })

        })
      },
      resetScreenSize(){
        let screenWidth = document.body.clientWidth;
        if(screenWidth < 500){
          this.drawerWidth = screenWidth;
        }else{
          this.drawerWidth = 700;
        }
      },
      onSearchStroageUser (){
        this.$refs.stroageUserModel.showStorageInfo('ok');
      },
      onStroageUserOk (selectionRows, num) {
        this.form.setFieldsValue({storekeeperId: selectionRows.id})
        this.form.setFieldsValue({storekeeperName: selectionRows.realname})
      },
      onSearchDepart (){
        this.$refs.departModel.showSelectDepartTreeModal('ok');
      },
      onDepartOk (selectionRows, num) {
        this.form.setFieldsValue({departId: selectionRows.key})
        this.form.setFieldsValue({departName: selectionRows.label})
      },
      add () {
        this.edit({});
      },
      edit (record) {

        this.condition = false;
        // this.seen = false;
        this.visible = true;
        this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
        this.form.resetFields();
        //选中节点加载当前节点的内容
        this.loadTree();
        getAction(this.url.searchQuery,{ id : key }).then((res)=>{
          if(res.success){
            this.model = Object.assign({}, res.result);
            this.model.parentId = res.result.parentId!=null?res.result.parentId.toString():null;
            this.$nextTick(() => {
              this.form.setFieldsValue(pick(this.model,'id','parentCode','name','code','storekeeperName','storekeeperId','departName','departId','warehouse','house','row','layer','box','isLeaf'))
            });
          }else{
            this.$message.warning(res.message);
          }
        })

        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'id','parentCode','name','code','storekeeperName','storekeeperId','departName','departId','warehouse','house','row','layer','box','isLeaf'))
        })
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'name','code','storekeeperName','storekeeperId','departName','departId','position','location','type'))
      },
    }
  }
</script>